import { MouseEventButton } from "@/const";
import { useDataViewStore } from "@/stores/dataview"
import { EditCanvasTypeEnum } from "@/stores/types";
import type { CreateComponentGroupType, CreateComponentType } from "@/views/dataview/packages/public/type";
import { cloneDeep, throttle } from "lodash";
import { toRaw } from "vue";

const dataviewStore = useDataViewStore()

export const useMouseHandle = ()=>{
    const mouseClickHandle = (e: MouseEvent, item:any) => {
        console.log("mouseClickHandle");
        
        e.preventDefault();
        e.stopPropagation();
        // 锁定了就不处理
        if (item.status.lock) return
        // 按下ctrl代表多选
        if(e.ctrlKey){
            if(dataviewStore.dataviewState.targetChart.selectId.includes(item.id)){
                // 已选中则取消选中
                const res = dataviewStore.dataviewState.targetChart.selectId.filter((id:string)=>id !== item.id)
                dataviewStore.setTargetSelectChart(res)
            }else{
                dataviewStore.setTargetSelectChart(item.id,true)
            }
        }
    }


    const mouseenterHandle = (e: MouseEvent, item: any) => {
        e.preventDefault()
        e.stopPropagation()
        if (!dataviewStore.getEditCanvas.isSelect) {
            dataviewStore.setTargetHoverChart(item.id)
        }
    }
    const mouseleaveHandle = (e:MouseEvent,item:any)=>{
        e.preventDefault()
        e.stopPropagation()
        dataviewStore.setEditCanvas(EditCanvasTypeEnum.IS_DRAG,false)
        dataviewStore.setTargetHoverChart(undefined)
    }

    const mousedownHandleUnStop = (e:MouseEvent,item?:any)=>{
        console.log("mousedownHandleUnStop")
        if(item){
            dataviewStore.setTargetSelectChart(item.id)
        }else{
            dataviewStore.setTargetSelectChart(undefined)
        }
    }
// 框选
    const mousedownBoxSelect = (e: MouseEvent, item?: CreateComponentType | CreateComponentGroupType)=>{
        console.log("mousedownBoxSelect")
        /* 
        1：鼠标左键
        2：鼠标中键（滚轮键）
        3：鼠标右键
        */
        if(e.which == 2) return

        mousedownHandleUnStop(e)
        // 记录起始位置
        const startOffetX = e.offsetX
        const startOffetY = e.offsetY
        const startScreenX = e.screenX
        const startScreenY = e.screenY
        const scale = dataviewStore.getEditCanvas.scale
        dataviewStore.setMousePosition(undefined,undefined,startOffetX,startOffetY)
    }
    // 位于画布中图表拖拽逻辑
    const mousedownHandle = (e:MouseEvent,item:any)=>{
        console.log("mousedownHandle");
        // mousedown只会执行一次 按下去一瞬间执行
        e.preventDefault()
        e.stopPropagation()
        if(item.status.lock) return //锁定了就不绑定移动处理逻辑

        // ctrl+左键点击
        if(e.buttons === MouseEventButton.LEFT && e.ctrlKey) return

        // 按下右键 + 选中多个 + 目标元素是多选子元素
        const selectId = dataviewStore.getTargetChart.selectId
        if(e.buttons === MouseEventButton.RIGHT && selectId.length>1&& selectId.includes(item.id)) return

        // 激活当前拖拽元素样式
        dataviewStore.setTargetSelectChart(item.id)

        if(e.buttons === MouseEventButton.RIGHT) return

        const scale = dataviewStore.getEditCanvas.scale
        const canvasWidth = dataviewStore.getEditCanvasConfig.width
        const canvasHeight = dataviewStore.getEditCanvasConfig.height

        
        // 记录初始位置大小
        const targetMap = new Map()
        dataviewStore.getTargetChart.selectId.forEach((id:any)=>{
            // 组件下标记录位置信息
            const index = dataviewStore.fetchTargetIndex(id)
            if(index !== -1){
                const {x,y,w,h} = toRaw(dataviewStore.getComponentList[index]).attr
                targetMap.set(id,{x,y,w,h})
            }
        })
        // 记录点击初始位置
        const startX = e.screenX
        const startY = e.screenY
        
        // 记录历史位置
        const prevComponentInstance:any[]= []
        dataviewStore.getTargetChart.selectId.forEach((id:any)=>{
            // 组件下标记录位置信息
            if(!targetMap.has(id)) return
            const index = dataviewStore.fetchTargetIndex(id)
            prevComponentInstance.push(cloneDeep(dataviewStore.getComponentList[index]))
        })
        dataviewStore.setMousePosition(undefined,undefined,startX,startY)

        // 移动-计算偏移量
        const mousemove = throttle((moveEvent:MouseEvent)=>{
            console.log("mousemove");
            
            // 设置当前元素正在拖拽中
            dataviewStore.setEditCanvas(EditCanvasTypeEnum.IS_DRAG,true)
            dataviewStore.setMousePosition(moveEvent.screenX,moveEvent.screenY)

            // 当前偏移量
            const offsetX = (moveEvent.screenX - startX) / scale
            const offsetY = (moveEvent.screenY - startY) / scale
            
            dataviewStore.getTargetChart.selectId.forEach((id:any)=>{
                if(!targetMap.has(id)) return
                // index执行到此一定不为-1
                const index = dataviewStore.fetchTargetIndex(id)
                const {x,y,w,h } = targetMap.get(id)
                const componentInstance = dataviewStore.getComponentList[index] //获取组件实例信息

                // 计算当前位置
                let curX = Math.round(x + offsetX)
                let curY = Math.round(y + offsetY)

                const distance = 50 //预留位置
                // 基于左上角检测
                curX = curX < -w + distance ? -w + distance + 25 : curX //添加25数值，不知道什么bug计算不对
                curY = curY < -h + distance ? -h + distance + 25  : curY

                
                // 基于右下角检测
                curX = curX > canvasWidth - distance? canvasWidth - distance : curX
                curY = curY > canvasHeight - distance? canvasHeight - distance : curY
                if(componentInstance){
                    componentInstance.attr = Object.assign(componentInstance.attr,{x:curX,y:curY})
                }
            })
            return
        },20)

        const mouseup = ()=>{
            console.log("mouseup");
            
            try{
                dataviewStore.setMousePosition(0,0,0,0)
                // 拖拽结束
                dataviewStore.setEditCanvas(EditCanvasTypeEnum.IS_DRAG,false)
                // 加入历史栈
                if(prevComponentInstance.length){
                    dataviewStore.getTargetChart.selectId.forEach((id:any)=>{
                        if(!targetMap.has(id)) return
                        // index执行到此一定不为-1
                        const index = dataviewStore.fetchTargetIndex(id)
                        const curComponentInstance = dataviewStore.getComponentList[index] //获取组件实例信息
                        // @ts-ignore
                        prevComponentInstance.forEach((preItem:any)=>{
                            if(preItem.id === id){
                                // 记录偏移量
                                preItem.attr = Object.assign(preItem.attr,{
                                    offsetX: curComponentInstance.attr.x - preItem.attr.x,
                                    offsetY: curComponentInstance.attr.y - preItem.attr.y
                                })
                            }
                        })
                        const moveComponentInstance = prevComponentInstance.filter(
                            item=>item.attr.offsetX != 0 && item.attr.offsetY!= 0
                        )
                        // 记录历史
                        moveComponentInstance.length && dataviewStore.moveComponentList(moveComponentInstance)
                    })
                }
                document.removeEventListener('mousemove',mousemove)
                document.removeEventListener('mouseup',mouseup)
            }catch(e){
                console.log(e);
            }
        }


        document.addEventListener('mousemove',mousemove)
        document.addEventListener('mouseup',mouseup)
    }
    return {
        mouseClickHandle,
        mouseenterHandle,
        mouseleaveHandle,
        mousedownHandleUnStop,
        mousedownHandle,
        mousedownBoxSelect
    }
}

// 处理锚点拖拽组件大小
export const useMousePointHandle = (e:MouseEvent,point:string,attr:any)=>{
    // point 是拖拽锚点的方位 t， lt，r，rt，b，lb，l，rb
    e.stopPropagation()
    e.preventDefault()
    dataviewStore.setEditCanvas(EditCanvasTypeEnum.IS_DRAG,true)
    const scale = dataviewStore.getEditCanvas.scale
    // 记录当前attr属性
    const itemAttrX = attr.x
    const itemAttrY = attr.y
    const itemAttrW = attr.w
    const itemAttrH = attr.h

    // 初始点击位置
    const startX = e.screenX
    const startY = e.screenY

    dataviewStore.setMousePosition(startX,startY)

    const handlemousemove = throttle((event:MouseEvent)=>{
        dataviewStore.setMousePosition(event.screenX,event.screenY)
        // 计算偏移量 分正负
        const offsetX = Math.round((event.screenX - startX) / scale)
        const offsetY = Math.round((event.screenY - startY) / scale)

        const isTop = /t/.test(point)
        const isLeft = /l/.test(point)
        const isRight = /r/.test(point)
        const isBottom = /b/.test(point)
       
        // 设置新宽高
        const newWidth = itemAttrW + (isLeft ? -offsetX : isRight ? offsetX : 0)
        const newHeight = itemAttrH + (isTop ? -offsetY : isBottom ? offsetY : 0)

        const min = 50 // 临界值
        attr.w = newWidth > min ? newWidth : min
        attr.h = newHeight > min ? newHeight : min
        attr.x = itemAttrX + (isLeft ? offsetX : 0)
        attr.y = itemAttrY + (isTop ? offsetY : 0)
    },20)

    const handlemouseup = (event:MouseEvent)=>{
        dataviewStore.setEditCanvas(EditCanvasTypeEnum.IS_DRAG,false)
        dataviewStore.setMousePosition(0,0,0,0)
        document.removeEventListener('mousemove',handlemousemove)
        document.removeEventListener('mouseup',handlemouseup)
    }

    document.addEventListener('mousemove',handlemousemove)
    document.addEventListener('mouseup',handlemouseup)
}

